//
//  MVDownloadOperation.m
//  Gegeda_music_MY
//
//  Created by lanou3g on 15/11/7.
//  Copyright © 2015年 周莹. All rights reserved.
//

#import "MVDownloadOperation.h"
#import "MVModel.h"
#define CachesPath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
#define k_videoDidDownedFinishedSuccess @"MVDidDownedSuccess"

@interface MVDownloadOperation ()<NSURLSessionDelegate,NSURLSessionDownloadDelegate>
{
    // 用于判断一个任务是否正在下载
    BOOL _isDownLoading;
    
}
@property(nonatomic, strong)MVModel *downLoadMVModel;
// 定义 session
@property(nonatomic, strong)NSURLSession *currentSession;
// 用于可恢复的下载任务的数据
@property(nonatomic, strong)NSData *partialData;
// 可恢复的下载任务
@property(nonatomic, strong)NSURLSessionDownloadTask *task;
@end


@implementation MVDownloadOperation

-(instancetype)initWithDownloadMVModel:(MVModel *)MVModel{
    self = [super init];
    if (self) {
        self.downLoadMVModel = MVModel;
    }
    return self;
}

-(void)main{
    NSURLSessionConfiguration *configure = [NSURLSessionConfiguration defaultSessionConfiguration];
    self.currentSession = [NSURLSession sessionWithConfiguration:configure delegate:self delegateQueue:nil];
    self.currentSession.sessionDescription = self.downLoadMVModel.url;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.downLoadMVModel.url]];
    self.task = [self.currentSession downloadTaskWithRequest:request];
    [self.task resume];
    _isDownLoading = YES;
    while (_isDownLoading) {
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
    }
    self.partialData = nil;
}

//暂停
-(void)downLoadPause{
    NSLog(@"暂停");
    [self.task suspend];
}

//恢复下载
-(void)downLoadResume{
    NSLog(@"回复下载");
    [self.task resume];
}

#pragma mark - 实现代理方法
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    NSLog(@"path= %@", location.path);
    //将临时文件夹剪切或者复制到caches文件夹
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *appendPath = [NSString stringWithFormat:@"/%@.mp4", self.downLoadMVModel.title];
    NSString *file = [CachesPath stringByAppendingString:appendPath];
    [manager moveItemAtPath:location.path toPath:file error:nil];
    _isDownLoading = NO;
    //下载完成后发送通知
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [[NSNotificationCenter defaultCenter] postNotificationName:k_videoDidDownedFinishedSuccess object:self.downLoadMVModel];
        self.downLoadMVModel.isDownFinished = YES;
        
    });
  
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    NSLog(@"--------%f", bytesWritten * 1.0 / totalBytesExpectedToWrite);
    
    
    
    self.downLoadMVModel.progressValue = totalBytesWritten / (double) totalBytesExpectedToWrite;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.updateBlock) {
            self.updateBlock(self.downLoadMVModel);
        }
    });
    
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
    
    NSLog(@"%.0f", fileOffset / (CGFloat) expectedTotalBytes);
}



@end
